# -*- coding: utf-8 -*-
import json
import urllib.request

# 请求地址
baseUrl = 'https://ins.popmars.com/instagram-service.php'
# 请求头部
headers = {
    'origin': 'https://ins.popmars.com',
    'referer': 'https://ins.popmars.com/',
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/82.0.4083.0 Safari/537.36 '
}
# 超时时间
timeout = 8

'''
    获取ios捷近传递的参数
'''


def get_url():
    if is_ins_url():
        # return 'https://www.instagram.com/p/Bbe-Zmzj9Fq/' # video
        # return 'https://www.instagram.com/p/B9Y4epbp4iS/?igshid=12034fmzcf9aq'  # media
        return 'https://www.instagram.com/p/B9lNta9ASja/?igshid=1odidu6lo928j'  # image
    return None


'''
    判断是否为ins路径
'''


def is_ins_url():
    return True


'''
    远程主机解析地址
'''


def remote_parse_urls(values):
    values = {
        'url': values
    }

    # 参数编码
    data = urllib.parse.urlencode(values).encode('utf-8')
    # 构建request头部
    req = urllib.request.Request(url=baseUrl, headers=headers, data=data, method='POST')

    try:
        # 发送请求，设置超时时间，s为单位
        response = urllib.request.urlopen(req, timeout=timeout).read()
        # 返回参数解码
        response = response.decode('utf-8')

        if len(response) == 0:
            print('字符串为空')
        else:
            result_data = json.loads(response)
            print(result_data)

            if result_data['status'] == 'success':
                print('请求成功')

                flag_ = result_data['flag']

                urls = []

                if flag_ == 'image':
                    urls = result_data['image']
                elif flag_ == 'video':
                    urls = result_data['videourl']
                elif flag_ == 'media':
                    urls = result_data['medias']
                    result_urls = []
                    for u in urls:
                        result_urls.append(u[0])

                    urls = result_urls

                download_resource(urls)
            else:
                # 提示请求失败
                print('请求失败')

    except Exception as e:
        print(e)
        # 错误结束程序
        exit(0)


'''
    下载图片
'''


def download_resource(paths):
    print(paths)


'''
    入口函数
'''
if __name__ == '__main__':

    url = get_url()
    if len(url) > 0:
        remote_parse_urls(url)
